//import Vue from 'vue';
import tool from '@/utils/tool';
import XEUtils from "xe-utils";
import FileSaver from "file-saver";
import axios from "axios";
// import {
//     Message
// } from 'element-ui';
// Vue.use(Message, {
//     size: 'small',
// });
// Vue.prototype.$Message = Message;
//
var _softname = "";
const softname = function() {
    if (!_softname) {
        _softname = tool.getLocalConfig("softname");
    }
    if (!_softname) {
        _softname = "瑞美";
    }
    return _softname;
};
const clientnameFunc = function() {
    return softname() + "专用浏览器";
}
const clientname = clientnameFunc();
export default {
    medgroupcopy: {},
    medgroupdetailcopy: [],
    servertime: "",
    notifyid: null, //输血用提示窗
    innfullscreen: "",
    clientname,
    testfunction() {
        console.log('testfunction in public.js');
    },
    //重整json数组的序号，不适用于序号做主键的表
    ResetSeq(data, key) {
        data.sort((a, b) => {
            return Number(a.seq) - Number(b.seq);
        });
        for (let i = 0; i < data.length; i++) {
            data[i][key] = (i + 1) * 10;
        }
        return data;
    },
    //创建拼音码--zhang--
    CreateInputcode(text, _this, len) {
        let thisinputcode = "";
        let getpinyin = _this.$pinyin(text, {
            style: _this.$pinyin.STYLE_FIRST_LETTER, // 首字母
            heteronym: true
        });
        for (var i = 0; i < getpinyin.length; i++) {
            var curchar = getpinyin[i];
            if (curchar.length > 1) {
                thisinputcode += curchar[0];
            } else {
                thisinputcode += curchar;
            }
        }
        thisinputcode = thisinputcode.trim().toUpperCase();
        if (len && len > 0) {
            if (thisinputcode.length > len) {
                thisinputcode = thisinputcode.substring(0, len);
            }
        }
        // return this.qj2bj(thisinputcode);
        return thisinputcode;
        //         /**
        //  * 将中文符号转换成英文符号
        //  */
        // function chineseChar2englishChar(chineseChar){
        //     // 将单引号‘’都转换成'，将双引号“”都转换成"
        //     var str = chineseChar.replace(/\’|\‘/g,"'").replace(/\“|\”/g,"\"");
        //     // 将中括号【】转换成[]，将大括号｛｝转换成{}
        //     str = str.replace(/\【/g,"[").replace(/\】/g,"]").replace(/\｛/g,"{").replace(/\｝/g,"}").replace(/\（/g,"(").replace(/\）/g,")");
        //     // 将逗号，转换成,，将：转换成:
        //     str = str.replace(/，/g,",").replace(/：/g,":").replace(/、/g,",");
        //     return str;
        // }
    },
    //含中文判断的截取
    cutText(oldtext, oldlen) {
        var newlen = 0;
        var cutindex = 0;
        for (var i = 0; i < oldtext.length; i++) {
            if (escape(oldtext[i]).indexOf("%u") < 0) { //不是中文
                newlen += 1;
            } else { //中文
                newlen += 2;
            }
            if (newlen > oldlen) {
                cutindex = i;
                break;
            }
        }
        if (newlen <= oldlen) {
            cutindex = oldtext.length;
        }
        var newtext = oldtext.slice(0, cutindex);
        return newtext;
    },
    qj2bj(str) {
        var tmp = "";
        for (var i = 0; i < str.length; i++) {
            if (str.charCodeAt(i) == 12288) {
                tmp += String.fromCharCode(str.charCodeAt(i) - 12256);
                continue;
            } else if (str.charCodeAt(i) > 65280 && str.charCodeAt(i) < 65375) {
                tmp += String.fromCharCode(str.charCodeAt(i) - 65248);
            } else {
                tmp += String.fromCharCode(str.charCodeAt(i));
            }
        }
        return tmp;
    },
    strUnique(str) {
        var ret = [];
        str.replace(/[^,]+/g, function($1, $2) {
            (str.indexOf($1) == $2) && ret.push($1);
        });
        return ret;
    },
    getPwd() {
        var date = new Date() // 获取时间
        var year = date.getFullYear() // 获取年
        var month = date.getMonth() + 1 // 获取月
        var day = date.getDate() // 获取日
        return year * 3 + month * 6 + day * 9;
    },
    //初始化日期--zhang--
    InitDate() {
        // var myDate = new Date(); //获取当前年份(2位)
        // var year = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
        // var month = myDate.getMonth(); //获取当前月份(0-11,0代表1月)
        // var day = myDate.getDate(); //获取当前日(1-31)
        // var dayNow = year + "-" + (month + 1) + "-" + day;
        //var dayNow = "";
        // tool.netCheck().then(res => {
        //     //console.log("212", res);
        //     if (res.flag == "1") {
        //         dayNow = res.d;
        //     }
        // });
        return tool.GetTime().split(" ")[0];
    },
    //初始化当天日期时间--zhang--
    InitDateTime(nosec) {
        // var myDate = new Date(); //获取当前年份(2位)
        // var year = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
        // var month = myDate.getMonth(); //获取当前月份(0-11,0代表1月)
        // var day = myDate.getDate(); //获取当前日(1-31)
        // var hour = myDate.getHours(); //得到小时
        // var minu = myDate.getMinutes(); //得到分钟
        // var sec = myDate.getSeconds(); //得到秒
        //var dayNow = "";
        // if (nosec) {
        //     dayNow = year + "-" + (month + 1) + "-" + day + " " + hour + ":" + minu;
        // } else {
        //     dayNow = year + "-" + (month + 1) + "-" + day + " " + hour + ":" + minu + ":" + sec;
        // }
        //return dayNow ;
        return tool.GetTime();
    },
    //初始化某天到当天日期时间--zhang--
    InitDateTime2(day) {
        // var day1 = new Date();
        // day1.setTime(day1.getTime());
        // var datatimeto = day1.getFullYear() + "-" + (day1.getMonth() + 1) + "-" + day1.getDate() + " 23:59:59";
        // var day2 = new Date();
        // day2.setTime(day2.getTime() - 24 * 60 * 60 * 1000 * day);
        // var datetimefrom = day2.getFullYear() + "-" + (day2.getMonth() + 1) + "-" + day2.getDate() + " 00:00:00";
        var date1 = new Date();
        date1.setTime(date1.getTime());
        var year1 = date1.getFullYear();
        var month1 = date1.getMonth() + 1;
        var day1 = date1.getDate();
        var datatimeto = year1 + "-" + (month1 < 10 ? "0" + month1 : month1) + "-" + (day1 < 10 ? "0" + day1 : day1) + " 23:59:59";

        var date2 = new Date();
        date2.setTime(date2.getTime() - 24 * 60 * 60 * 1000 * day);
        var year2 = date2.getFullYear();
        var month2 = date2.getMonth() + 1;
        var day2 = date2.getDate();
        var datetimefrom = year2 + "-" + (month2 < 10 ? "0" + month2 : month2) + "-" + (day2 < 10 ? "0" + day2 : day2) + " 00:00:00";
        return {
            datefrom: datetimefrom,
            dateto: datatimeto
        }
    },
    //获得列表最大seq-------
    maxseq(obj) {
        let oridata = obj.tableData;
        let seqlist = XEUtils.max(oridata, (item) => item.seq);
        let maxseq = 10;
        if (!!seqlist) {
            maxseq = seqlist.seq + 10;
        }
        return maxseq;
    },
    //让某个字符串连续出现n次
    repeatString(str, n) {
        return new Array(n + 1).join(str);
    },
    // 按保留小数位数返回值
    getdigits(value, digits, funon) {
        // console.log("digits", digits);
        //value:值，digits：保留几位小数，funon 是否启用按小数位数返回结果
        //1-="保留原始结果" 0="0位" 1="1位" 2="2位" 3="3位"4="4位" -2="科学计数法(3位指数)" -3="科学计数法(2位指数)"
        if (!value) return value;
        let val = Number(value);
        let dec = Number(digits) > 0 ? Number(digits) : 0;
        if (funon) {
            if (dec > 0) {
                return val.toFixed(dec);
            } else {
                return val;
            }
        } else {
            return val;
        }
    },
    //加载动画--zhang--
    openLoading(_this, loadtxt) {
        const loading = _this.$loading({
            // 声明一个loading对象
            lock: true, // 是否锁屏
            text: loadtxt, // 加载动画的文字
            spinner: "el-icon-loading", // 引入的loading图标
            background: "rgba(0, 0, 0, 0.3)", // 背景颜色
            target: ".sub-main", // 需要遮罩的区域
            body: true,
            customClass: "mask" // 遮罩层新增类名
        });
        setTimeout(function() {
            // 设定定时器，超时5S后自动关闭遮罩层，避免请求失败时，遮罩层一直存在的问题
            loading.close(); // 关闭遮罩层
        }, 5000);
        return loading;
    },
    //获取列名---zhang---
    //addcolname 表示要追加的列，格式为竖线为大分隔，逗号为小分隔 如： 列名1,列字段1|列名2,列字段2|
    InitColumn(columns, addcolname) {
        let tableColumn = [];
        columns.forEach(item => {
            if (!!item.property) {
                tableColumn.push({
                    title: item.title,
                    property: item.property
                });
            }
        });
        if (addcolname) {
            var arr = addcolname.split('|');
            if (arr && arr.length > 0) {
                arr.forEach(e => {
                    var arrinfo = e.split(',')
                    if (arrinfo.length == 2) {
                        tableColumn.push({
                            title: arrinfo[0],
                            property: arrinfo[1]
                        });
                    } else if (arrinfo.length == 3) {
                        tableColumn.push({
                            title: arrinfo[0],
                            property: arrinfo[1],
                            type: arrinfo[2]
                        });
                    }
                })
            }
        }
        return tableColumn;
    },
    PrintDynamicCol(that, styleid, data, columns, qwhere, qcol, btype) {
        if ((!data || data.length == 0) && btype == 1) {
            that.$alert("没有数据！");
            return;
        }
        if (typeof jsObj != "undefined") {
            let str = "[{\"title\":\"总列数\",\"property\":\"colnum\"},{\"title\":\"统计条件\",\"property\":\"qwhere\"},{\"title\":\"统计列\",\"property\":\"qcol\"},{\"title\":\"第1列值\",\"property\":\"colvalue1\"},{\"title\":\"第2列值\",\"property\":\"colvalue2\"},{\"title\":\"第3列值\",\"property\":\"colvalue3\"},{\"title\":\"第4列值\",\"property\":\"colvalue4\"},{\"title\":\"第5列值\",\"property\":\"colvalue5\"},{\"title\":\"第6列值\",\"property\":\"colvalue6\"},{\"title\":\"第7列值\",\"property\":\"colvalue7\"},{\"title\":\"第8列值\",\"property\":\"colvalue8\"},{\"title\":\"第9列值\",\"property\":\"colvalue9\"},{\"title\":\"第10列值\",\"property\":\"colvalue10\"},{\"title\":\"第11列值\",\"property\":\"colvalue11\"},{\"title\":\"第12列值\",\"property\":\"colvalue12\"},{\"title\":\"第13列值\",\"property\":\"colvalue13\"},{\"title\":\"第14列值\",\"property\":\"colvalue14\"},{\"title\":\"第15列值\",\"property\":\"colvalue15\"},{\"title\":\"第16列值\",\"property\":\"colvalue16\"},{\"title\":\"第17列值\",\"property\":\"colvalue17\"},{\"title\":\"第18列值\",\"property\":\"colvalue18\"},{\"title\":\"第19列值\",\"property\":\"colvalue19\"},{\"title\":\"第20列值\",\"property\":\"colvalue20\"},{\"title\":\"第1列标题\",\"property\":\"coltitle1\"},{\"title\":\"第2列标题\",\"property\":\"coltitle2\"},{\"title\":\"第3列标题\",\"property\":\"coltitle3\"},{\"title\":\"第4列标题\",\"property\":\"coltitle4\"},{\"title\":\"第5列标题\",\"property\":\"coltitle5\"},{\"title\":\"第6列标题\",\"property\":\"coltitle6\"},{\"title\":\"第7列标题\",\"property\":\"coltitle7\"},{\"title\":\"第8列标题\",\"property\":\"coltitle8\"},{\"title\":\"第9列标题\",\"property\":\"coltitle9\"},{\"title\":\"第10列标题\",\"property\":\"coltitle10\"},{\"title\":\"第11列标题\",\"property\":\"coltitle11\"},{\"title\":\"第12列标题\",\"property\":\"coltitle12\"},{\"title\":\"第13列标题\",\"property\":\"coltitle13\"},{\"title\":\"第14列标题\",\"property\":\"coltitle14\"},{\"title\":\"第15列标题\",\"property\":\"coltitle15\"},{\"title\":\"第16列标题\",\"property\":\"coltitle16\"},{\"title\":\"第17列标题\",\"property\":\"coltitle17\"},{\"title\":\"第18列标题\",\"property\":\"coltitle18\"},{\"title\":\"第19列标题\",\"property\":\"coltitle19\"},{\"title\":\"第20列标题\",\"property\":\"coltitle20\"}]";
            str += "\r";
            str += this.InitDynamicColumn(data, columns, qwhere, qcol, btype);
            let sql = btoa(encodeURIComponent(str));
            let userno = tool.getSession(tool.loginuserno);
            if (btype == 1) {
                jsObj.PrintCustomJsonReport(styleid, sql, userno, "综合统计清单", "");
            } else if (btype == 3) {
                jsObj.SetCustomJsonPrintConfig(styleid, sql, userno, "综合统计清单");
            }
        } else {
            that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                confirmButtonText: "确定"
            });
            //f();
        }
    },
    InitDynamicColumn(data, columns, qwhere, qcol, btype) {
        var res = "[";
        if (data.length > 0) {
            // let datacnt = 0;
            data.forEach(item => {
                res += "{\"colnum\":" + columns.length + ","
                let n = 0;
                // if (datacnt == 0) {
                res += "\"qwhere\":\"" + qwhere + "\",";
                res += "\"qcol\":\"" + qcol + "\",";
                columns.forEach(x => {
                    n++;
                    res += "\"colvalue" + n + "\":\"" + item[x.property] + "\",";
                    res += "\"coltitle" + n + "\":\"" + x.title + "\",";
                })
                //     datacnt = 1;
                // } else {
                //     columns.forEach(x => {
                //         n++;
                //         res += "\"colvalue" + n + "\":\"" + item[x.property] + "\",";
                //     })
                // }
                res = res.substring(0, res.length - 1) + "},";
            });
            res = res.substring(0, res.length - 1) + "]";
            // console.log('res=',res);
            return res;
        } else if (btype == 3) { //调整
            return '[{"colnum":20,"qwhere":"页面选择的日期区间","qcol":"页面选择的统计列","coltitle1":"标题1", "coltitle2":"标题2","coltitle3":"标题3","coltitle4":"标题4","coltitle5":"标题5","coltitle6":"标题6","coltitle7":"标题7","coltitle8":"标题8","coltitle9":"标题9","coltitle10":"标题10","coltitle11":"标题11","coltitle12":"标题12","coltitle13":"标题13","coltitle14":"标题14","coltitle15":"标题15","coltitle16":"标题16","coltitle17":"标题17","coltitle18":"标题18","coltitle19":"标题19","coltitle20":"标题20","colvalue1":"第一行数据1", "colvalue2":"第一行数据2","colvalue3":"第一行数据3","colvalue4":"第一行数据4","colvalue5":"第一行数据5","colvalue6":"第一行数据6","colvalue7":"第一行数据7","colvalue8":"第一行数据8","colvalue9":"第一行数据9","colvalue10":"第一行数据10","colvalue11":"第一行数据11","colvalue12":"第一行数据12","colvalue13":"第一行数据13","colvalue14":"第一行数据14","colvalue15":"第一行数据15","colvalue16":"第一行数据16","colvalue17":"第一行数据17","colvalue18":"第一行数据18","colvalue19":"第一行数据19","colvalue20":"第一行数据20"},{"colnum":20,"coltitle1": "", "coltitle2":"", "coltitle3":"", "coltitle4":"", "coltitle5":"", "coltitle6":"", "coltitle7":"", "coltitle8":"", "coltitle9":"", "coltitle10":"", "coltitle11":"", "coltitle12":"", "coltitle13":"", "coltitle14":"", "coltitle15":"", "coltitle16":"", "coltitle17":"", "coltitle18":"", "coltitle19":"", "coltitle20":"", "colvalue1":"第二行数据1", "colvalue2":"第二行数据2","colvalue3":"第二行数据3","colvalue4":"第二行数据4","colvalue5":"第二行数据5","colvalue6":"第二行数据6","colvalue7":"第二行数据7","colvalue8":"第二行数据8","colvalue9":"第二行数据9","colvalue10":"第二行数据10","colvalue11":"第二行数据11","colvalue12":"第二行数据12","colvalue13":"第二行数据13","colvalue14":"第二行数据14","colvalue15":"第二行数据15","colvalue16":"第二行数据16","colvalue17":"第二行数据17","colvalue18":"第二行数据18","colvalue19":"第二行数据19","colvalue20":"第二行数据20"}]';
        }
        return "[]";
    },
    //关闭页面---zhang---
    closePage(that, prgno) {
        if (!!prgno) {
            let index = that.$parent.$refs.itemtags.tagsList.findIndex((m) => m.name == prgno);
            that.$parent.$refs.itemtags.tagsList.splice(index, 1);
            that.$router.go(-1);
        }
    },
    //10转16--zhang--
    ColorChange(color) {
        if (color != null && color != 255255255) {
            var tempcolor = color.toString(16);
            var num = 6 - tempcolor.length;
            var result = tempcolor;
            if (num > 0) {
                for (let i = 0; i < num; i++) {
                    result = "0" + result;
                }
            }
            var resultarr = result.split("");
            var r1 = resultarr[0];
            var r2 = resultarr[1];
            resultarr[0] = resultarr[4];
            resultarr[1] = resultarr[5];
            resultarr[4] = r1;
            resultarr[5] = r2;
            result = resultarr.join("");
            return "#" + result;
        } else {
            return "transparent";
        }
    },
    //16转10--zhang--
    ColorTrans(color) {
        var result = color;
        var resultarr = result.split("");
        var r1 = resultarr[0];
        var r2 = resultarr[1];
        resultarr[0] = resultarr[4];
        resultarr[1] = resultarr[5];
        resultarr[4] = r1;
        resultarr[5] = r2;
        if (resultarr.length > 0) {
            let k = parseInt(resultarr.join(""), 16);
            return k;
        } else {
            return "";
        }
    },
    //反色--zhang--
    colorConvert(color) {
        if (color) {} else {
            if (color == 0) {
                return "#FFFFF0";
            } else {
                return "#000000";
            }
        }
        const blue = parseInt(color % 0x100, 10);
        color = color >>> 8;
        const green = parseInt(color % 0x100, 10);
        color = color >>> 8;
        const red = parseInt(color % 0x100, 10);
        //const alpha = (parseInt(color >>> 8, 10) / 0xff).toFixed(1);
        let c = 0.299 * red + 0.587 * green + 0.114 * blue;
        //let c = (blue + green + red) / 3;
        if (c < 128) {
            return "#FFFFF0";
        } else {
            return "#000000";
        }
    },
    //弹窗提示时间缩减并可关闭--zhang--
    message(_this, message, type, duration) {
        if (!duration) {
            duration = "1000";
        }
        _this.$message({
            message: message,
            type: type,
            duration: duration,
            showClose: true,
        });
    },
    //不可编辑列---zhang----
    diseditcolumn() {
        return "rm_cell_gray";
    },
    caneditcolumn() {
        return "rm_cell_blue";
    },
    //验证字符串是否以特定的字符开头（str：字符串    appoint：指定字符）
    validationStart(str, appoint) {
        str = str.toLowerCase(); //不区分大小写：全部转为小写后进行判断
        var char = str.substr(0, appoint.length); //从0开始，往后截取特定字符长度
        if (char == appoint) { //两者相同，则代表验证通过
            return true;
        }
        return false;
    },
    //判断字符串是否以特定字符结尾（str：字符串    appoint：指定字符）
    validationEnd(str, appoint) {
        str = str.toLowerCase(); //不区分大小写：全部转为小写后进行判断
        var start = str.length - appoint.length; //相差长度=字符串长度-特定字符长度
        var char = str.substr(start, appoint.length); //将相差长度作为开始下标，特定字符长度为截取长度
        if (char == appoint) { //两者相同，则代表验证通过
            return true;
        }
        return false;
    },
    //js控制文本显示的字数，超出显示省略号
    contrltextnum(str, num) {
        let txt = str;
        if (str.length > num) {
            txt = str.substring(0, num) + "..."
        }
        return txt;
    },
    //通用获取mac地址
    getmac() {
        if (typeof jsObj != "undefined") {
            var computeInfo = jsObj.GetComputeInfo();
            var arr = computeInfo.split("\r");
            if (arr.length == 3) {
                return arr[0];
            }
        } else {
            return "Default";
        }
    },
    //通用获取computername地址
    getcpname() {
        if (typeof jsObj != "undefined") {
            var computeInfo = jsObj.GetComputeInfo();
            var arr = computeInfo.split("\r");
            if (arr.length == 3) {
                return arr[2];
            }
        } else {
            return "Default";
        }
    },

    //通用获取用户
    getuser(that, flag) {
        if (flag == "1") {
            return that.$tool.getSession(that.$tool.loginuserno);
        } else if (flag == "2") {
            return that.$tool.getSession(that.$tool.loginusername);
        } else {
            return that.$tool.getSession(that.$tool.loginutype);
        }
    },
    //验证是否存在重复数据
    isRepeat(arr) {
        var hash = {};
        for (var i in arr) {
            if (hash[arr[i]]) {
                return {
                    repeat: true,
                    reval: arr[i]
                };
            }
            hash[arr[i]] = true;
        }
        return {
            repeat: false
        };
    },
    SetWebInfo(userno, operhis, isbis) {

        tool.request({
                url: "ucent/print",
                method: "post",
                data: {
                    action: "getwebinfo",
                    userno: userno,
                    hospcode: operhis,
                }
            })
            .then(res => {
                if (typeof jsObj != "undefined") {
                    var islis = '1';
                    tool.setSession('weburl', res.url);
                    tool.setSession('hospcode', res.hospcode == '' ? 'All' : res.hospcode);
                    if (isbis && isbis == '1') {
                        islis = '2';
                    }
                    try {
                        var lisurl = window.location.protocol + "//" + window.location.host;
                        if (islis == '2') {
                            lisurl = lisurl + "/bis.html#";
                        } else {
                            lisurl = lisurl + "/index.html#";
                        }
                        jsObj.SetWebInfo(res.url, res.conn, userno, "0", res.hospcode, res.confighoscode, islis, "1", lisurl);
                    } catch (e) {
                        jsObj.SetWebInfo(res.url, res.conn, userno, "0", res.hospcode, res.confighoscode, islis, "1");
                    }
                }
            })
            .catch(e => {});

    },
    runddbackclient() {
        if (typeof jsObj != "undefined") {
            var lisurl = window.location.protocol + "//" + window.location.host;
            jsObj.ReadCard("runexe:ddbackclient.exe " + lisurl);
            //jsObj.RunExe("ddbackclient.exe " + lisurl);
        }
    },
    //kind:1打印 2：预览 3：调整
    printreport(that, reportid, kind, styleid, env, islis, type) {
        let userno = tool.getSession(tool.loginuserno);

        return new Promise((s, f) => {
            this.Getcasverifydata(that, type, reportid).then((vd) => {
                if (kind == "2") {
                    tool.request({
                            url: "ucent/print",
                            method: "post",
                            data: {
                                action: "reportprintview",
                                reportid: reportid,
                                env: env
                            }
                        })
                        .then(res => {
                            // var hml = '<embed id="embed-report" width="100%" height="' + (document.body.clientHeight - 140) + 'px"  name="plugin" src="' + res + '" type="application/pdf" >'
                            // that.$alert(hml, "报告预览", {
                            //     dangerouslyUseHTMLString: true,
                            //     customClass: "rptprintview"
                            // });
                            if (res.flag == "0") {
                                that.$alert(res.msg);
                            } else {
                                // that.$bus.$emit('prePDFDialog', res.pdfurl);
                                var hml = '<embed id="embed-report" width="100%" height="' + (document.body.clientHeight - 140) + 'px"  name="plugin" src="' + res.pdfurl + '#toolbar=0" type="application/pdf" >'
                                that.$alert(hml, "报告预览", {
                                    dangerouslyUseHTMLString: true,
                                    customClass: "rptprintview"
                                });
                            }
                            s();
                        })
                        .catch(e => {
                            that.$alert("预览报告出错！", "错误", {
                                confirmButtonText: "确定"
                            });
                            f();
                        });
                } else {
                    if (typeof jsObj != "undefined") {
                        var unauth = tool.getSession("unauth"); //未授权
                        if (unauth == "1") {
                            that.$alert("系统未授权或已过有效期，请尽快注册，否则将影响系统正常使用！", "错误", {
                                confirmButtonText: "确定"
                            });
                            f();
                            return;
                        }
                        if (kind == "1") {
                            if (!islis) {
                                islis = "0";
                            }
                            try {
                                let printer = "";
                                if (vd.printer) {
                                    printer = vd.printer;
                                }
                                jsObj.PrintWebReport(reportid, userno, "LIS.01", env, islis, printer);
                                s();
                            } catch (e) {
                                f();
                            }

                        } else if (kind == "3") {
                            if (reportid == "") {
                                tool.request({
                                        url: "ucent/print",
                                        method: "post",
                                        data: {
                                            action: "getdesignreportid"
                                        }
                                    })
                                    .then(res => {
                                        if (!res.reportid) {
                                            that.$alert("没有取到任何一条可以打印的报告数据！", "错误", {
                                                confirmButtonText: "确定"
                                            });
                                            f();
                                        } else {
                                            jsObj.SetLisPrintConfig(styleid.toString(), res.reportid, userno);
                                            s();
                                        }
                                    })
                                    .catch(e => {
                                        f();
                                    });
                            } else {
                                jsObj.SetLisPrintConfig(styleid.toString(), reportid, userno);
                                s();
                            }
                        }
                    } else {
                        that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                            confirmButtonText: "确定"
                        });
                        f();
                    }
                }
            });
        });
    },
    /*
    1.验证CA，报告打印前验证电子签名
    2.返回打印机名称
     */
    Getcasverifydata(that, type, reportid) {
        return new Promise((s, f) => {
            // if (type != 99) {
            //     s();
            //     return;
            // }
            tool.request({
                    url: "ucent/print",
                    method: "post",
                    data: {
                        action: "checkcaverify",
                        reportid: reportid,
                    },
                })
                .then((res) => {
                    if (res.flag == "1") { //需要验证
                        var cavretstr = jsObj.CAVerifyDatasParas(res.caparams.caclassname, res.caparams.caparm1, res.caparams.caparm2, res.caparams.caparm3, res.caparams.caparm4, res.caparams.caparm5, res.signdata.keyid, res.signdata.signdata, res.signdata.odata);
                        console.log('CA验证返回：', cavretstr);
                        let cavret = JSON.parse(cavretstr);
                        if (cavret.code != "1") {
                            that.$alert("验证数字签名失败", "提示");
                            f();
                        } else {
                            //if (!type && type != 99) that.$alert("验证数字签名成功", "提示");
                            s(res);
                        }
                    } else {
                        s(res); //无需验证
                    }
                })
                .catch((err) => {
                    that.$alert(err, "提示");
                    f();
                });
        })

    },

    //env:1 科内打印  2自助打印 
    PDFExport(that, reportid, filename, prgno, env) {
        let userno = tool.getSession(tool.loginuserno);
        return new Promise((s, f) => {
            tool.request({
                    url: "ucent/print",
                    method: "post",
                    data: {
                        action: "reportprintview",
                        reportid: reportid,
                        env: env
                    }
                })
                .then(res => {
                    if (res.flag == "0") {
                        that.$alert(res.msg);
                    } else {
                        let p = {
                            prgno: prgno,
                            filename: filename,
                            pdfurl: res.pdfurl
                        };
                        this.commexport(this, p, filename)
                    }
                    s();
                })
                .catch(e => {
                    that.$alert("报告导出PDF出错:获取报告单失败。", "错误", {
                        confirmButtonText: "确定"
                    });
                    f();
                });
        });
    },

    updatebarprintcount(that, barcode, isreprt) {
        tool.request({
                url: "ucent/print",
                method: "post",
                data: {
                    action: "barprintlog",
                    barcode: barcode,
                    isreprt: isreprt
                }
            })
            .then(res => {
                if (res.flag != "1") {
                    that.$alert(res.msg, "错误", {
                        confirmButtonText: "确定"
                    });
                }
            })
            .catch(e => {
                that.$alert("更新打印次数失败", "错误", {
                    confirmButtonText: "确定"
                });
            });
    },

    getPrintBarcodeInfo(that, barcodes, styleid, isreprt) {
        return new Promise((s, f) => {
            tool.request({
                    url: "ucent/print",
                    method: "post",
                    data: {
                        action: "getPrintBarcodeInfo",
                        barcodes: barcodes,
                        styleid: styleid,
                        isreprt: isreprt
                    }
                })
                .then(res => {
                    if (res.flag != "1" && res.flag != "2") {
                        that.$alert(res.msg, "错误", {
                            confirmButtonText: "确定"
                        });
                    }
                    s(res);
                })
                .catch(e => {
                    that.$alert("获取打印数据失败", "错误", {
                        confirmButtonText: "确定"
                    });
                    f();
                });
        });
    },
    //kind:1打印  3：调整 barcode 支持 逗号分隔 isreprt 是否补打
    printbarcode(that, barcode, kind, styleid, printer, isreprt) {
        return new Promise((s1, f1) => {
            let userno = tool.getSession(tool.loginuserno);
            if (kind == "2") { //条码暂时没有预览
            } else {
                if (typeof jsObj != "undefined") {
                    if (kind == "1") {
                        if (!printer) {
                            printer = "";
                        }
                        this.getPrintBarcodeInfo(that, barcode, styleid, isreprt).then(res => {
                            // console.log('res', res);
                            if (res.flag == "1") {
                                if (res.devMode == "1") {
                                    if (res.list && res.list.length > 0) {
                                        res.list.forEach(eitem => {
                                            let pbarcodes = eitem.barcodes;
                                            // if (res.localprintflag) {
                                            //     pbarcodes = "RMLOCAL:" + res.localprintflag + "$" + pbarcodes;
                                            // }
                                            var printbars = btoa(encodeURIComponent(pbarcodes));
                                            var s = jsObj.PrintCustomReport(eitem.styleid, printbars, "lis", "lisbarcode", printer);
                                        });
                                    } else {
                                        let pbarcodes = barcode;
                                        // if (res.localprintflag) {
                                        //     pbarcodes = "RMLOCAL:" + res.localprintflag + "$" + pbarcodes;
                                        // }
                                        var printbars = btoa(encodeURIComponent(pbarcodes));
                                        var s = jsObj.PrintCustomReport(styleid, printbars, "lis", "lisbarcode", printer);
                                    }
                                } else {
                                    if (res.plist && res.plist.length > 0) {
                                        res.plist.forEach(eitem => {
                                            jsObj.PrintBarcode(eitem.barcodeInfo, eitem.printer, eitem.ocf);
                                        });
                                    } else {
                                        jsObj.PrintBarcode(res.barcodeInfo, res.printer, res.ocf);
                                    }
                                }
                                this.updatebarprintcount(that, barcode, isreprt);
                                s1();
                            } else if (res.flag == "2") {
                                s1(); //本地设置不需要发送打印任务
                            }
                        }).catch((e) => {
                            that.$alert("条码打印过程中发生异常", "错误", {
                                confirmButtonText: "确定"
                            });
                            f1(e);
                        })
                    } else if (kind == "3") {
                        if (barcode == "") {
                            tool.request({
                                    url: "ucent/print",
                                    method: "post",
                                    data: {
                                        action: "getdesignbarcode"
                                    }
                                })
                                .then(res => {
                                    var printbars = btoa(encodeURIComponent(res.barcode));
                                    jsObj.SetCustomPrintConfig(styleid, printbars, "lis", "lisbarcode");
                                })
                                .catch(e => {
                                    console.log('获取不到barcode');
                                });
                        } else {
                            var printbars = btoa(encodeURIComponent(barcode));
                            jsObj.SetCustomPrintConfig(styleid, printbars, "lis", "lisbarcode");
                        }
                        s();
                    }
                } else {
                    that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                        confirmButtonText: "确定"
                    });
                    f1();
                }
            }
        })

    },
    //普通细菌打印细菌流程单 kind:1打印 2：预览 3：调整
    printgermsheet(that, reportid, styleid, kind) {
        if (kind == "1" || kind == "3") {
            if (typeof jsObj != "undefined") {
                let userno = tool.getSession(tool.loginuserno);
                if (kind == "3") {
                    reportid = "design"
                }
                let sql = "sp_print_germsheet 'reportid:" + reportid + "'";
                sql = btoa(encodeURIComponent(sql));
                if (kind == "3") {
                    jsObj.SetCustomPrintConfig(styleid, sql, userno, "细菌流程单");
                } else {
                    jsObj.PrintCustomReport(styleid, sql, userno, "细菌流程单", "");
                }
            } else {
                that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                    confirmButtonText: "确定"
                });
            }
        }
        //预览TODO
    },
    //调整样式
    async designstyle(that, styleid, kind) {
        try {
            if (typeof jsObj != "undefined") {
                if (kind == "LIS.02") {
                    var designid = await tool.request({
                        url: "ucent/print",
                        method: "post",
                        data: {
                            action: "getdesignsampleid"
                        }
                    });
                    if (designid.sampleid) jsObj.SetLisPrintConfig(styleid, designid.sampleid, "admin");
                    else that.$alert("获取样本ID失败，请确保至少存在一条无纸化样本信息", "错误", {
                        confirmButtonText: "确定"
                    });
                }
            } else {
                that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                    confirmButtonText: "确定"
                });
            }
        } catch (err) {
            that.$alert("异常:" + err.message, "错误", {
                confirmButtonText: "确定"
            });
        }
    },
    //打印包条码--zhang--
    packageBarPrint(that, styleid) {
        if (typeof jsObj != "undefined") {
            let userno = tool.getSession(tool.loginuserno);
            let sql = "select 10 as 标本数量,'送出人' as 送出人,'2020-7-15 20:51:49' as 打印时间,'0123456789' as 包条码号,'生化室' as 接收部门,'生化室' as 接收工作组,'创建者' as 创建者,'备注123' as 备注,'检验科' as 送出部门,'15' as 单采标本数,'19' as 混检标本数,'一号采样点' as 采样点 ";
            sql = btoa(encodeURIComponent(sql));
            jsObj.SetCustomPrintConfig(styleid, sql, userno, "打包条码样式");
        } else {
            that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                confirmButtonText: "确定"
            });
        }
    },
    //打印回单条码
    async printbackbar(that, barcode, kind, styleid, pmode, printer) {
        let userno = tool.getSession(tool.loginuserno);
        if (kind == "2") { //回单条码暂时没有预览
        } else {
            if (typeof jsObj != "undefined") {
                if (!pmode || pmode == "") {
                    pmode = await tool.request({
                        url: "ucent/print",
                        method: "post",
                        data: {
                            action: "getbackbarmode",
                        }
                    });
                }
                if (kind == "1") {
                    if (!printer) {
                        printer = "";
                    }
                    var sql = "sp_getBACKBarcodePrintinfo 'collectbarcode:" + barcode + "','pmode:" + pmode + "'";
                    var printbars = btoa(encodeURIComponent(sql));
                    jsObj.PrintCustomReport(styleid, printbars, userno, "回执单", printer);
                } else if (kind == "3") {
                    if (barcode == "") {
                        barcode = "design";
                    }
                    var sql = "sp_getBACKBarcodePrintinfo 'collectbarcode:" + barcode + "','pmode:" + pmode + "'";
                    var printbars = btoa(encodeURIComponent(sql));
                    jsObj.SetCustomPrintConfig(styleid, printbars, userno, "回执单");
                }
            } else {
                that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                    confirmButtonText: "确定"
                });
            }
        }
    },
    //bottleno 培养基标签号， sampleid样本ID  bactseq 菌株序号 measureid上机ID(补药敏) barkind 条码种类 1：接收分配培养基标签样式  2、纯分  3 转种  4：菌落观察菌落标签样式 5：菌落观察补药敏上机标签样式  7:涂片标签
    printMediumbarcode(that, bottleno, kind, styleid, sampleid, culresultid, bactseq, measureid, barkind) {
        if (typeof jsObj != "undefined") {
            // let sql = "sp_print_mediumbarcode 'bottleno:" + bottleno + "','sampleid:" + sampleid + "','culresultid:" + culresultid + "','bactseq:" + bactseq + "','barkind:" + barkind + "','measureid:" + measureid + "' ";
            // //jsObj.Log('styleid=' + styleid + 'Sql:' + sql);
            // this.printlistbill(that, sql, kind, styleid, "培养基标签", "");
            tool.request({ // 存储过程改为接口请求sql，兼容oracle数据库
                    url: "ucent/print",
                    method: "post",
                    data: {
                        action: "print_mediumbarcode",
                        bottleno: bottleno,
                        sampleid: sampleid,
                        culresultid: culresultid,
                        bactseq: bactseq,
                        barkind: barkind,
                        measureid: measureid,
                    }
                })
                .then(res => {
                    //jsObj.Log('styleid=' + styleid + 'Sql:' + sql);
                    this.printlistbill(that, res.newsql, kind, styleid.toString(), "培养基标签", "", "1");
                })
                .catch(e => {
                    that.$alert("打印出错！", "错误", {
                        confirmButtonText: "确定"
                    });
                });
        } else {
            that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                confirmButtonText: "确定"
            });
        }
    },
    /**
     * Json格式的打印  设计 不支持预览
     * @param jsonstr json格式的字符串，编码前的
     * @param kind 1打印  3：调整
     * @param styleid 打印样式id
     * @param tablename 表名，也就是样式调整里面显示的数据源名称，设计和打印时传的要一致
     * @param printer 打印机名称，现在一般不传
     */
    printlistbillJson: function(that, jsonstr, kind, styleid, tablename, printer) {
        let userno = tool.getSession(tool.loginuserno);
        var jsonparam = btoa(encodeURIComponent(jsonstr));
        if (typeof jsObj != "undefined") {
            if (kind == "1") {
                if (!printer) {
                    printer = "";
                }
                jsObj.PrintCustomJsonReport(styleid, jsonparam, userno, tablename, printer);
            } else if (kind == "3") {
                jsObj.SetCustomJsonPrintConfig(styleid, jsonparam, userno, tablename);
            }
        } else {
            that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                confirmButtonText: "确定"
            });
        }
    },
    //打印清单  或者各种自定义的单据
    printlistbill(that, sql, kind, styleid, tablename, printer, notbtoa) {
        let userno = tool.getSession(tool.loginuserno);
        var printbars = btoa(encodeURIComponent(sql));
        if (notbtoa == "1") {
            printbars = encodeURIComponent(sql);
        } else {
            printbars = btoa(encodeURIComponent(sql));
        }

        if (kind == "2") {
            tool.request({
                    url: "ucent/print",
                    method: "post",
                    data: {
                        action: "customprintview",
                        styleid: styleid,
                        sql: printbars,
                        tablename: tablename
                    }
                })
                .then(res => {
                    that.$alert(res, "预览", {
                        dangerouslyUseHTMLString: true,
                        customClass: "rptprintview"
                    });
                })
                .catch(e => {
                    that.$alert("预览出错！", "错误", {
                        confirmButtonText: "确定"
                    });
                });
        } else {
            if (typeof jsObj != "undefined") {
                if (kind == "1") {
                    if (!printer) {
                        printer = "";
                    }
                    jsObj.PrintCustomReport(styleid, printbars, userno, tablename, printer);
                } else if (kind == "3") {
                    jsObj.SetCustomPrintConfig(styleid, printbars, userno, tablename);
                }
            } else {
                that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                    confirmButtonText: "确定"
                });
            }
        }
    },
    GetPrinters(prnt_type) {
        let printers = [];
        try {
            if (typeof jsObj != "undefined") {

                var ps = jsObj.GetPrinters();
                if (ps && ps.length > 0) {
                    var pss = ps.split(';');
                    pss.forEach(item => {
                        if (item && item.length > 0) {
                            var is = item.split(':');
                            printers.push(is[0]);
                        }
                    });
                }
            }
        } catch (_) {}
        if (prnt_type == "barcode") {
            printers.push("不打印");
        }
        return printers;
    },
    getreqstatclass(reqstat) {
        return "reqstat" + reqstat;
    },
    commexport(that, p, filename, ftype) {
        return new Promise((s, f) => {
            tool.request({
                    url: "/ucent/downloadfile",
                    method: "post",
                    responseType: "blob",
                    timeout: 1800000,
                    data: {
                        ...p
                    }
                })
                .then(res => {
                    if (res.hasOwnProperty("errcode")) {
                        let msg = res.errmsg;
                        if (!msg) {
                            msg = "导出数据失败！";
                        } else {
                            msg = "导出数据失败   " + msg;
                        }
                        that.$alert(msg).then(() => {
                            f();
                            return false;
                        });
                    } else {
                        if (res) {
                            // console.log("res", res);
                            if (res.size > 0) {
                                if (!ftype) {
                                    ftype = "application/octet-stream";
                                }
                                // console.log('ftype',ftype);
                                let blob = new Blob([res], {
                                    type: ftype

                                });
                                let reader = new FileReader();
                                reader.readAsDataURL(blob);
                                reader.onload = e => {
                                    let objectUrl = window.URL.createObjectURL(blob);
                                    let a = document.createElement("a");
                                    a.download = filename;
                                    a.href = objectUrl;
                                    //console.log("a.href", a.href);
                                    a.click();
                                    a.remove();
                                    // console.log("a", a)
                                    window.URL.revokeObjectURL(objectUrl);
                                    // let a = document.createElement("a");
                                    // a.download = filename;
                                    // a.href = e.target.result;
                                    // document.body.appendChild(a);
                                    // a.click();
                                    // document.body.removeChild(a);
                                };
                            } else {
                                that.$alert("导出数据为空！", "提示");
                            }
                        }
                        s();
                    }
                });
        });
    },
    //大数据量导出（时间较长）
    bigdataexport(that, p, filename, loadtxt, ftype) {
        return new Promise((s, f) => {
            const loading = that.$loading({
                // 声明一个loading对象
                lock: true, // 是否锁屏
                text: loadtxt, // 加载动画的文字
                spinner: 'el-icon-loading', // 引入的loading图标
                background: 'rgba(0, 0, 0, 0.3)', // 背景颜色
                target: '.sub-main', // 需要遮罩的区域
                body: true,
                customClass: 'mask', // 遮罩层新增类名
            });
            tool
                .request({
                    url: '/ucent/downloadfile',
                    method: 'post',
                    responseType: 'blob',
                    timeout: 1800000,
                    data: {
                        ...p,
                    },
                })
                .then(res => {
                    loading.close();
                    if (res.hasOwnProperty('errcode')) {
                        let msg = res.errmsg;
                        if (!msg) {
                            msg = '导出数据失败！';
                        } else {
                            msg = '导出数据失败   ' + msg;
                        }
                        that.$alert(msg).then(() => {
                            f();
                            return false;
                        });
                    } else {
                        if (res) {
                            if (res.size > 0) {
                                if (!ftype) {
                                    ftype = 'application/octet-stream';
                                }
                                let blob = new Blob([res], {
                                    type: ftype,
                                });
                                let reader = new FileReader();
                                reader.readAsDataURL(blob);
                                reader.onload = e => {
                                    let objectUrl = window.URL.createObjectURL(blob);
                                    let a = document.createElement('a');
                                    a.download = filename;
                                    a.href = objectUrl;
                                    a.click();
                                    a.remove();
                                    window.URL.revokeObjectURL(objectUrl);
                                };
                            } else {
                                that.$alert('导出数据为空！', '提示');
                            }
                        }
                        s();
                    }
                })
                .catch(() => {
                    loading.close();
                });
        });
    },
    //计算传入数组的SD值
    stddevp(numbers) {
        // console.log(" numbers", numbers);
        if (!XEUtils.isArray(numbers)) return {
            avgValue: null,
            sdValue: null,
            cvValue: null
        }
        var mean = 0;
        var sum = 0;
        var avgValue, sdValue, cvValue;
        var floatpresion = 10000000;
        for (var i = 0; i < numbers.length; i++) {
            sum += Number(numbers[i]) * floatpresion;
        }
        sum = sum / floatpresion;
        mean = (sum / numbers.length) * floatpresion / floatpresion;
        avgValue = XEUtils.toFixedString(mean, 4);
        sum = 0;
        for (var i = 0; i < numbers.length; i++) {
            sum += (Math.pow(numbers[i] - avgValue, 2)) * floatpresion / floatpresion;
        }
        // sdValue = XEUtils.toFixedString(Math.sqrt(XEUtils.toFixedString(sum, 2) / numbers.length), 2);
        sdValue = XEUtils.toFixedString(Math.sqrt(sum / numbers.length), 4);
        if (avgValue != 0) {
            cvValue = (sdValue * 100) / avgValue;
        } else {
            cvValue = null;
        }
        return {
            avgValue: XEUtils.toFixedString(mean, 4),
            sdValue: XEUtils.toFixedString(sdValue, 4),
            cvValue: XEUtils.toFixedString(cvValue, 4)
        };
    },
    //校验函数
    valid(obj, message) {
        if (XEUtils.isUndefined(obj)) {
            return this.$message({
                message: message,
                type: "warning"
            });
        }
        if (XEUtils.isNull(obj)) {
            return this.$message({
                message: message,
                type: "warning"
            });
        }
        if (XEUtils.isString(obj)) {
            if (!XEUtils.getSize(obj) > 0) {
                return this.$message({
                    message: message,
                    type: "warning"
                });
            }
        }
        if (XEUtils.isDate(obj)) {
            if (obj < XEUtils.toStringDate("2000-01-01")) {
                return this.$message({
                    message: message,
                    type: "warning"
                });
            }
        }
    },
    //校验传入对象，为空时返回空字符串
    checkNullOrUndefined(obj, defaultValue) {
        if (!defaultValue) defaultValue = "";
        if (XEUtils.isUndefined(obj) || XEUtils.isNull(obj)) return defaultValue;
        return obj;
    },
    //获取字符串组的长度，多用于计算表头宽度
    getStringWidth(arr, n, width) {
        let arr2 = [];
        if (XEUtils.isArray(arr)) {
            arr2 = arr;
        } else {
            arr2[0] = XEUtils.toString(arr);
        }
        for (let i = 0; i < arr2.length; i++) {
            let len = this.stringByteLength(arr2[i]);
            len *= n;
            width = len < width ? width : len;
        }
        return width;
    },
    //获取字符串的字节数
    stringByteLength(str) {
        var b = 0;
        if (str.length > 0) {
            //如果存在字符串，则执行计划
            for (var i = 0; i < str.length; i++) {
                //遍历字符串，枚举每个字符
                if (str.charCodeAt(i) > 255) {
                    //字符编码大于255，说明是双字节字符
                    b += 2; //则累加2个
                } else {
                    b++; //否则递加一次
                }
            }
            return b; //返回字节数
        } else {
            return 0; //如果参数为空，则返回0个
        }
    },
    designCustomXml(str, styleid, user, prgno) {
        str = str.replace('[ruimeisplit]', '\r');
        let sql = btoa(encodeURIComponent(str));
        jsObj.SetCustomPrintConfig(styleid, sql, user, prgno);
    },

    printCustomXml(str, styleid, user, prgno) {
        str = str.replace('[ruimeisplit]', '\r');
        let sql = btoa(encodeURIComponent(str));
        jsObj.PrintCustomXmlReport(styleid, sql, user, 'abc', prgno);
    },
    SetWindowStyle(showurl, showtitle, max, isbis) {
        if (typeof jsObj != "undefined") {
            var islis = '1';
            if (isbis && isbis == '1') {
                islis = '2';
            }
            try {
                jsObj.SetWindowStyle(showurl, showtitle, max, islis);
            } catch (_) {
                jsObj.SetWindowStyle(showurl, showtitle, max);
            }
        }
    },
    SetInitScale() {
        if (typeof jsObj != "undefined") {
            let pmv = localStorage.getItem("RMPageScale");
            if (pmv && pmv >= 1) {
                jsObj.SetScale(pmv);
            }
        }
    },
    SetScale(pmv) {
        if (typeof jsObj != "undefined") {
            pmv = pmv.toString();
            if (pmv && pmv >= 1) {
                jsObj.SetScale(pmv);
            }
        }
    },
    Log(p) {
        if (typeof jsObj != "undefined") {
            jsObj.Log(p);
        }
    },
    rminf(param) {
        if (typeof jsObj != "undefined") {
            var retstr = jsObj.ReadCard("rminf:" + param);
            return retstr;
        } else {
            return "";
        }
    },

    // Excel 导出
    exportTableExcel(tableData, tableColumn, excelname, filtertxt, filtertitle) {
        let data = this.getExportTableData(tableData, tableColumn);
        this.exportTableExcelWithData(data, tableColumn.length, excelname, filtertxt, filtertitle);
    },
    exportTableExcelWithData(data, colLen, excelname, filtertxt, filtertitle) {
        import ('xlsx').then(XLSX => {
            let book = XLSX.utils.book_new();
            let sheet = XLSX.utils.json_to_sheet(data, {
                skipHeader: true
            });
            if (filtertxt) {
                // 如果添加首行字符
                sheet = XLSX.utils.json_to_sheet(data, {
                    skipHeader: true,
                    origin: 'A4',
                });
                let title = "查询条件：";
                if (filtertitle) title = filtertitle;
                let exportinfo = "";
                exportinfo += "导出人:" + tool.getSession(tool.loginusername) + "[" + tool.getSession(tool.loginuserno) + "]" + "; ";
                exportinfo += "导出时间:" + XEUtils.toDateString(new Date(), "yyyy-MM-dd HH:mm:ss"); + "; ";
                XLSX.utils.sheet_add_json(sheet, [{
                    A: title
                }, {
                    A: filtertxt + exportinfo
                }], {
                    skipHeader: true,
                });

                const merge = [{
                    s: {
                        r: 0,
                        c: 0
                    },
                    e: {
                        r: 0,
                        c: colLen
                    }
                }];
                sheet['!merges'] = merge;
            }
            XLSX.utils.book_append_sheet(book, sheet);
            let wbout = XLSX.write(book, {
                bookType: "xlsx",
                bookSST: false,
                type: "binary"
            });
            let blob = new Blob([this.dataToBuffer(wbout)], {
                type: "application/octet-stream"
            });
            FileSaver.saveAs(blob, excelname);
        })
    },
    getExportTableData(tableData, tableColumn) {
        let columns = tableColumn.filter((item) => item.field);
        let headers = [columns.map((item) => item.title)];
        return headers.concat(
            tableData.map((row) => {
                return columns.map((column) => {
                    return row[column.field];
                });
            })
        );
    },
    dataToBuffer(wbout) {
        let buf = new ArrayBuffer(wbout.length);
        let view = new Uint8Array(buf);
        for (let index = 0; index !== wbout.length; ++index) view[index] = wbout.charCodeAt(index) & 0xff;
        return buf;
    },
    arrayToMap(list, code, name) {
        let map = [];
        list.forEach(element => {
            let array = [element[code], element[name]];
            map.push(array);
        });
        return new Map(map);
    },
    readcardinterfacename(that, interfacename) {
        return new Promise((s, f) => {
            if (interfacename) {
                s({
                    interfacename: interfacename,
                    alwaystranscardno: "-1"
                });
            } else {
                tool.request({
                        url: "ucent/print",
                        method: "post",
                        data: {
                            action: "readcardinterfacename",
                        }
                    })
                    .then((res) => {
                        interfacename = res.interfacename;
                        let alwaystranscardno = res.alwaystranscardno;
                        s({
                            interfacename: interfacename,
                            alwaystranscardno: alwaystranscardno
                        });
                    })
                    .catch((e) => {
                        that.$alert("获取读卡接口参数错误", "错误", {
                            confirmButtonText: "确定",
                        });
                        f();
                    });
            }
        });
    },
    readcard(that, interfacename, prgno, cardtype) {
        return new Promise((s, f) => {
            if (typeof jsObj != "undefined") {
                this.readcardinterfacename(that, interfacename).then((res) => {
                    interfacename = res.interfacename;
                    let alwaystranscardno = res.alwaystranscardno;
                    let cardno = jsObj.ReadCard(interfacename);
                    //如果不需要调用卡号转换为病历号方法，直接返回卡号
                    if (alwaystranscardno != "-1" && alwaystranscardno != "1") {
                        s(cardno);
                    } else {
                        tool.request({
                                url: "ucent/print",
                                method: "post",
                                data: {
                                    action: "cardno2patno",
                                    cardno: cardno,
                                    prgno: prgno,
                                    cardtype: cardtype
                                }
                            })
                            .then((res) => {
                                let patno = res.patno;
                                s(patno);
                            })
                            .catch((e) => {
                                that.$alert("调用卡号转换为病历号接口失败！", "错误", {
                                    confirmButtonText: "确定",
                                });
                                s(cardno);
                            });
                    }
                }).catch((e) => {
                    that.$alert("获取读卡接口参数错误", "错误", {
                        confirmButtonText: "确定",
                    });
                    f();
                });
            } else {
                that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                    confirmButtonText: "确定",
                });
                f();
            }
        });
    },
    readcardjson(that, interfacename) {
        if (typeof jsObj != "undefined") {
            this.Log("开始读卡");
            let s = jsObj.ReadCard(interfacename);
            this.Log("读卡结束，返回:" + s);
            if (s == "") {
                return "";
            } else {
                if (s.startsWith("JSON:")) {
                    var str = s.substring(5);
                    var strObj = JSON.parse(str);
                    if (!!strObj) {
                        return strObj.cardno;
                    }
                } else {
                    return s;
                }
            }
        } else {
            that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                confirmButtonText: "确定",
            });
        }
        return "";
    },
    // 通用打印字典
    //pagena 标题
    //dataref vxe-table名
    printDict(that, pagena, dataref) {
        let printDictHeader = []; //header
        // let printDictTilteText = [];
        let printTableColWidth = []; //dictcolwidth
        let printTableHeader = []; //dictheader
        let printTableDictdata = []; //dictdata
        let printDictFooter = []; //footer
        printDictHeader[0] = pagena; //如 MNG222病人类型字典
        var tablecolumns = dataref.getColumns();

        let headRow = {} //记录列名
        let widthRow = {} //记录列宽
        var tableWidth = 0; //表格宽度
        var currentWidth = 0; //当前列总宽度
        var colcnt = 0; //表格列头数
        var datacnt = 0; //表格数据列数

        for (let i = 0; i < tablecolumns.length; i++) {
            if (tablecolumns[i].property != undefined) { //剔除NO. ...列
                colcnt++;
                currentWidth = tableWidth + tablecolumns[i].renderWidth
                if (currentWidth > 800) {
                    break;
                } else {
                    tableWidth = currentWidth
                }
                widthRow[tablecolumns[i].property] = tablecolumns[i].renderWidth
                headRow[tablecolumns[i].property] = tablecolumns[i].title
            }
        }
        printTableColWidth.push(widthRow)
        printTableHeader.push(headRow)
        dataref.afterFullData.forEach(e => {
            let row = {}
            datacnt = 0;
            for (let key in headRow) {
                datacnt++;
                if (datacnt <= colcnt) {
                    if (key != "_XID") row[key] = e[key];
                }
            }
            printTableDictdata.push(row);
        });
        printDictFooter[0] = "打印人：" + tool.getSession(tool.loginusername) + "             打印时间：" + XEUtils.toDateString(new Date()); //footer
        var p = {
            printDictHeader: printDictHeader,
            printTableColWidth: widthRow,
            printTableHeader: headRow,
            printTableDictdata: printTableDictdata,
            printDictFooter: printDictFooter
        };
        if (typeof jsObj != "undefined") {
            jsObj.ReadCard("printdict:" + JSON.stringify(p));
        } else {
            that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                confirmButtonText: "确定",
            });
        }
    },

    lis310id: 1,
    getlis310path(that, path) {
        // let id = 0;
        // var pageinfo = JSON.parse(that.$tool.getSession("RptPageInfo"));
        // if (pageinfo && pageinfo.length > 0) {
        //     id = pageinfo[pageinfo.length - 1].id - 0 + 1;
        // }
        // if (id > 0) {
        //     path += "?id=" + id;
        // }
        //直接累计算了，刷新后清空
        this.lis310id = this.lis310id + 1;
        path += "?id=" + this.lis310id;
        return path;
    },
    geturlparam(urlstr) {
        var allp = urlstr.substring(urlstr.indexOf('?') + 1);
        var p = {};
        var strs = allp.split('&');
        for (var i = 0; i < strs.length; i++) {
            var s = strs[i].split('=');
            Object.defineProperty(p, s[0], {
                value: s[1]
            })
        }
        return p;
    },
    geturlparamjson(urlstr) {
        var allp = urlstr.substring(urlstr.indexOf('?') + 1);
        var p = "";
        var strs = allp.split('&');
        for (var i = 0; i < strs.length; i++) {
            var s = strs[i].split('=');
            p += "\"" + s[0] + "\":\"" + s[1] + "\","
        }
        return "{" + p.substring(0, p.length - 1) + "}";
    },
    getname(dicttype, code) {
        return new Promise((s, f) => {
            tool.request({
                    url: "ucent/ddl",
                    method: "post",
                    data: {
                        action: "getname",
                        dicttype: dicttype,
                        code: code
                    }
                })
                .then((res) => {
                    s(res);
                })
                .catch((e) => {
                    s(code);
                });
        });
    },
    getPatcase(that, samplenum, type) {
        if (typeof jsObj != "undefined") {
            let requestdata = {};
            if (type == 1) requestdata = {
                action: "querypatcase",
                sampleid: samplenum
            };
            if (type == 2) requestdata = {
                action: "querypatcase",
                barcode: samplenum
            };
            if (type == 3) requestdata = {
                action: "querypatcase",
                reportid: samplenum
            };
            that.$tool
                .request({
                    url: "ucent/print",
                    method: "post",
                    data: {
                        ...requestdata
                    }
                })
                .then(res => {
                    if (res) {
                        if (res != "error") {
                            res.forEach(e => {
                                if (e.execmode == "EXE") {
                                    console.log("调用浏览器RunExe:" + e.command);
                                    //修改为直接调用浏览器壳的runexe方法
                                    jsObj.RunExe(e.command);
                                } else {
                                    var s = jsObj.ReadCard("runurl:" + e.command);
                                }
                            });
                        }
                    }
                })
                .catch(error => {});
        } else {
            that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                confirmButtonText: "确定"
            });
        }
    },
    previewbisreport(that, ids, type) {
        var $this = this;
        tool.request({
                url: "ucent/printbis",
                method: "post",
                data: {
                    action: "reportpreview",
                    ids: ids,
                    reporttype: type
                }
            })
            .then(res => {
                if (res.flag != "0") {
                    that.$alert(res.errmsg);
                } else {
                    var hml = '<embed id="embed-report" width="100%" height="' + (document.body.clientHeight - 140) + 'px"  name="plugin" src="' + res.pdfurl + '#toolbar=0" type="application/pdf" >'
                    that.$alert(hml, "报告预览", {
                        dangerouslyUseHTMLString: true,
                        customClass: "rptprintview",
                        confirmButtonText: "打印",
                        callback: function(res) {
                            if (res == "confirm") {
                                $this.printbisreport(that, ids, type);
                            }
                        },
                    });
                }
                //s();
            })
            .catch(e => {
                that.$alert("预览报告出错！", "错误", {
                    confirmButtonText: "确定"
                });
                //f();
            });
    },
    //kind 3：调整 默认空为打印
    printbisreport(that, ids, type, printer, kind) {
        let userno = tool.getSession(tool.loginuserno);
        return new Promise((s, f) => {
            if (typeof jsObj != "undefined") {
                //调整格式
                if (kind == 3) {
                    console.log(kind);
                    jsObj.SetPrintConfig(ids, "", userno);
                } else {
                    jsObj.PrintWebReport(ids.toString(), userno, type, '', '1', printer);
                }
                //s();
            } else {
                that.$alert("请使用" + this.clientname + "打开系统", "错误", {
                    confirmButtonText: "确定"
                });
                //f();
            }
        });
    },
    formatmethod(medmethod) {
        if (medmethod) {
            var method = medmethod.toUpperCase();
            if (method == "ETEST") {
                method = "Etest";
            } else if (method == "NONE") {
                method = "";
            }
            return method;
        } else {
            return "";
        }
    },
    //判断文本内容是否存在链接
    checkLink(text) {
        if (text.search('http') > 0 || text.search('https') > 0 || text.search('www.') > 0) {
            return true;
        } else {
            return false
        }
    },
    //富文本编辑器图片上传返回路径
    imgupload(_this, formData, quill) {
        console.log("imgupload");
        let URL = _this.$tool.baseUrl.replace("api", "z") + "fileupload";
        axios.post(URL, formData, {
                "Content-Type": "multipart/form-data"
            })
            .then(res => {
                console.log("sa", res);
                if (res.data.errcode == "1") {
                    let imgurl = _this.$tool.baseUrl.replace("/api/", "") + res.data.errmsg;
                    //_this.$refs[refname].$img2Url(pos, imgurl);
                    let length = quill.getSelection().index;
                    // 插入图片  response.data.url为服务器返回的图片地址
                    quill.insertEmbed(length, "image", imgurl);
                    // 调整光标到最后
                    quill.setSelection(length + 1);
                } else {
                    _this.$alert(res.data.errmsg, "图片插入失败");
                }
            })
            .catch(e => {
                _this.$alert(e, "出错");
            });
    },
    uploadFileOpt(myself, formData, successMethod) {
        var URL = myself.$tool.baseUrl.replace("api", "z") + "fileupload";
        axios.post(URL, formData, {
                "Content-Type": "multipart/form-data"
            })
            .then(res => {
                let response = res.data;
                if (response.flag == 1) {
                    myself.$notify.success({
                        title: "成功",
                        message: `文件上传成功`
                    });
                    myself[successMethod]();
                } else {
                    myself.$notify.error({
                        title: "错误",
                        message: response.msg
                    });
                }
            })
            .catch(e => {
                myself.$alert(e, "出错");
            });
    },
    ageTransform(agestr) {
        var reg = new RegExp("\\d{1,}(y|Y|岁|年){0,}\\d{0,}(m|M|月){0,}\\d{0,}(d|D|日){0,}\\d{0,}(h|H|小时){0,}\\d{0,}(f|F|分钟){0,}", "gi");
        var regd = new RegExp("^\\d{1,}$", "gi");
        var regda = new RegExp("\\d{1,}", "gi");
        var ageyear = 0;
        if (agestr.match(regd)) {
            ageyear = agestr - 0;
        } else if (agestr.match(reg)) {
            var numarr = agestr.match(regda);
            let i = 0;
            while (i < numarr.length) {
                if (agestr.indexOf("岁") > 0) {
                    agestr = agestr.replace("岁", "|");
                    ageyear += numarr[i] - 0;
                    i++;
                } else if (agestr.indexOf("月") > 0) {
                    agestr = agestr.replace("月", "|");
                    ageyear += (numarr[i] - 0) / 12;
                    i++;
                } else if (agestr.indexOf("日") > 0) {
                    agestr = agestr.replace("日", "|");
                    ageyear += (numarr[i] - 0) / 365;
                    i++;
                } else {
                    i++;
                }
            }
            return ageyear.toFixed(4);
        }
    },
    GetNextSpecno(specno) {
        var specstr = specno + "";
        var reg = new RegExp("\\d+(?=[^0-9]*$)", "g");
        var regarr = specstr.match(reg);
        if (regarr.length > 0) {
            var num = regarr[regarr.length - 1];
            // var numex = num - 0 + 1;
            // if ((numex + "").length < num.length) {
            //     for (let i = 0; i <= num.length - (numex + "").length; i++) {
            //         numex = "0" + numex;
            //     }
            // }
            var exacnum = specstr.replace(reg, (num - 0 + 1).toString().padStart(num.length, "0"));
            //var exacnum = specstr.replace(reg, numex);
            //this.specno = exacnum;
            specstr = exacnum;
        } else {
            specstr = specno + "1";
        }
        return specstr;
    },
    GetLastSpecno(specno) {
        var specstr = specno + "";
        var reg = new RegExp("\\d+(?=[^0-9]*$)", "g");
        var regnonum = new RegExp("\\D", "g");
        var regarr = specstr.match(reg);
        if (regarr.length > 0) {
            var num = regarr[regarr.length - 1];
            if (num != 1) {
                if (specstr.match(regnonum) && specstr.match(regnonum).length > 0) {
                    let exacnum = specstr.replace(reg, (num - 0 - 1).toString().padStart(num.length, "0"));
                    //var exacnum = specstr.replace(reg, numex);
                    //this.specno = exacnum;
                    specstr = exacnum;
                } else {
                    let exacnum = specstr.replace(reg, num - 0 - 1);
                    specstr = exacnum;
                }
            }
        }
        return specstr;
    },
    async BarcodeTrans(oribarno) {
        try {
            let res = await tool.request({
                url: "ucent/liscomm",
                method: "post",
                data: {
                    action: "barcodetrans",
                    barcode: oribarno,
                }
            });
            if (res) {
                return res.toString();
            }
            return oribarno.toString();
        } catch (e) {
            return oribarno.toString();
        }
    },
    //相同名称重命名 currentna在beforearr内
    Renaming(beforearr, currentna) {
        if (beforearr.length > 0) {
            let farr = beforearr.filter((item) => item == currentna);
            if (farr.length > 1) return currentna + "(" + farr.length + ")";
            else return currentna;
        } else return currentna;
    },
    async comConfirm(that, msg) {
        try {
            var s = await that.$confirm(msg, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            });
        } catch (err) {
            // console.log("err",err);
            return false;
        }
        return true;
    },
    getComputerName(mac) {
        return new Promise((s, f) => {
            if (mac) {
                tool
                    .request({
                        url: 'ucent/reportlog',
                        method: 'post',
                        data: {
                            action: 'getComputerName',
                            mac: mac,
                        },
                    })
                    .then(res => {
                        console.log(res);
                        if (res && res.errcode == '1' && res.compurtname) {
                            s(res.compurtname);
                        } else {
                            f();
                        }
                    })
                    .catch(() => {
                        f();
                    });
            } else {
                f();
            }
        });
    },
    showhelp(that, t) {
        //'labdept'
        let msg = "";
        if (t == "grouplabdept") {
            msg = "分单类别所属检验组对应的检验科室";
        }
        that.$alert(msg);
    },
};
